﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;

using ProjManagSolution.pmMyWebService;

/*
 * NOTES: 1/sua lai ham lay involved project trong db de lay them cai role nua
 *
 * 
 */

namespace ProjManagSolution
{
    public partial class UserControlPanel : Page
    {
        pmWebServiceClient ws = new pmWebServiceClient();

        protected string userEmail;
        protected user curUser = new user();

        protected OwnedProjectItem selected = new OwnedProjectItem();
        InvolvedProjectItem selected_involved = new InvolvedProjectItem();

        // Naive code
        int index = 0;

        public UserControlPanel()
        {
            InitializeComponent();
            
            //get user by email
            GetUserByEmail();
            
        }

        protected void GetUserByEmail()
        {
            Session s = new Session();
            userEmail = s.GetUserEmail();
        
            ws.GetUserDetailByEmailCompleted += new EventHandler<GetUserDetailByEmailCompletedEventArgs>(ws_GetUserDetailByEmailCompleted);
            ws.GetUserDetailByEmailAsync(userEmail);
        }

        protected void ShowOwnedProject()
        {
            //get and show owned project
            ws.GetProjectsByManagerCompleted += new EventHandler<GetProjectsByManagerCompletedEventArgs>(ws_GetProjectsByManagerCompleted);
            ws.GetProjectsByManagerAsync(Convert.ToInt32(curUser.user_id));
        }

        protected void ShowInvolvedProject()
        {
            ws.GetInvolvedProjectsCompleted += new EventHandler<GetInvolvedProjectsCompletedEventArgs>(ws_GetInvolvedProjectsCompleted);
            ws.GetInvolvedProjectsAsync(Convert.ToInt32(curUser.user_id));
        }

        void ws_GetInvolvedProjectsCompleted(object sender, GetInvolvedProjectsCompletedEventArgs e)
        {
            List<project> input = new List<project>();
            input = e.Result;
            showInvolvedProjectList(input);
        }

        void ws_GetProjectsByManagerCompleted(object sender, GetProjectsByManagerCompletedEventArgs e)
        {
            List<project> input = new List<project>();
            input = e.Result;
            showOwnedProjectList(input);
        }

        void ws_GetUserDetailByEmailCompleted(object sender, GetUserDetailByEmailCompletedEventArgs e)
        {
            curUser = e.Result;
            //set the email textblock to email
            this.txtblokEmail.Text = curUser.user_email.ToString();

            //get and show owned project
            ShowOwnedProject();

            //get and show involved project
            ShowInvolvedProject();
        }

        // 
        protected void showOwnedProjectList(List<project> input)
        {
            List<OwnedProjectItem> ownedProjectList = new List<OwnedProjectItem>();

            for (int i = 0; i < input.Count; i++)
            {
                ownedProjectList.Add(new OwnedProjectItem()
                {
                    Id = input[i].project_id.ToString(),
                    Name = input[i].project_name.ToString(),
                    StartDate = input[i].project_start_date,
                    Description = input[i].project_description
                });
            }
            this.datagridOwnedProject.ItemsSource = ownedProjectList;
        }

        protected void showInvolvedProjectList(List<project> input)
        {
            List<InvolvedProjectItem> involvedProjectList = new List<InvolvedProjectItem>();
            string[] roleValue = new string[4] { "Project Manager", "Team Lead", "Team Member", "Observer" };

            for (int i = 0; i < input.Count; i++)
            {
                involvedProjectList.Add(new InvolvedProjectItem()
                {
                    Id = input[i].project_id.ToString(),
                    Name = input[i].project_name.ToString(),
                    StartDate = input[i].project_start_date,
                    Role = roleValue[i % 4],
                    Description = input[i].project_description
                });
            }
            this.datagridInvolvedProject.ItemsSource = involvedProjectList;
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void buttLogout_Click(object sender, RoutedEventArgs e)
        {
            PageSwitch ps = this.Parent as PageSwitch;
            ps.Navigate(new MainPage());
        }

        //CREATE PROJECT - Begin
        private void buttNewProject_Click(object sender, RoutedEventArgs e)
        {
            CreateProject cp = new CreateProject(curUser);
            cp.Closed += new EventHandler(cpClose);
            cp.Show();
        }
        void cpClose(object sender, EventArgs e)
        {
            CreateProject cp = (CreateProject)sender;

            if (cp.DialogResult == true)
            {
                //project newProject = new project();
                //newProject.manager_id = curUser.user_id;
                //newProject.project_name = cp.txtboxProjectName.Text.ToString();
                //newProject.project_start_date = DateTime.Today;
                //newProject.project_end_date = DateTime.Today;
                //newProject.project_description = cp.txtboxDescription.Text.ToString();

                //project newProject = new project();
                //newProject.manager_id = Convert.ToInt32(curUser.user_id);
                //newProject.project_name = cp.txtboxProjectName.Text.ToString();
                //newProject.project_start_date = DateTime.Today;
                //newProject.project_end_date = Convert.ToDateTime("1/1/2100");
                //newProject.project_description = cp.txtboxDescription.Text.ToString();

                //pmWebServiceClient t = new pmWebServiceClient();
                //t.InsertProjectCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(t_InsertProjectCompleted);
                //t.InsertProjectAsync(newProject);
                //ws.InsertProjectCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(ws_InsertProjectCompleted);
                //ws.InsertProjectAsync(newProject);

                pmWebServiceClient tido = new pmWebServiceClient();
                tido.InsertProjectNewCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(ws_InsertProjectNewCompleted);
                tido.InsertProjectNewAsync(curUser.user_id, cp.txtboxProjectName.Text, cp.txtboxDescription.Text, DateTime.Today, DateTime.Today);
            }
        }

        void ws_InsertProjectNewCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            MessageBox.Show("Project is created successfully!");
            ShowOwnedProject();
        }


        //void ws_InsertProjectCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        //{
        //    MessageBox.Show("Project is created successfully!");
        //}
        //Insert project - END

        //EDIT OWNED PROJECT
        private void buttEdit_Click(object sender, RoutedEventArgs e)
        {
            //if a project is selected to edit
            //pass the project id to edit project pop up
            if (datagridOwnedProject.SelectedIndex >= 0)
            {
                selected = (OwnedProjectItem)datagridOwnedProject.SelectedItem;
                int pid = Convert.ToInt32(selected.Id);

                EditProject ep = new EditProject(pid);
                ep.Closed += new EventHandler(epClose);
                ep.Show();
            }
            else
            {
                MessageBox.Show("Choose a project to Edit!");
            }
        }
        void epClose(object sender, EventArgs e)
        {
            EditProject ep = (EditProject)sender;

            if (ep.DialogResult == true)
            {
                project updated = new project();

                updated.project_id = Convert.ToInt32(selected.Id);
                updated.project_name = ep.txtboxProjectName.Text;
                updated.project_start_date = Convert.ToDateTime(ep.txtblokStartDate.Text);
                updated.project_description = ep.txtboxDescription.Text;
                updated.manager_id = curUser.user_id;
                updated.project_end_date = DateTime.Now;

                pmWebServiceClient tido = new pmWebServiceClient();
                tido.UpdateProjectDetailsCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(ws_UpdateProjectDetailsCompleted);
                tido.UpdateProjectDetailsAsync(updated.project_id, updated);
            }
        }

        void ws_UpdateProjectDetailsCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            MessageBox.Show("Project is updated successfully!");
            ShowOwnedProject();
        }

        //DELETE A PROJECT
        private void buttDelete_Click(object sender, RoutedEventArgs e)
        {
            if (datagridOwnedProject.SelectedIndex >= 0)
            {
                //get the selected project
                selected = (OwnedProjectItem)datagridOwnedProject.SelectedItem;

                ConfirmWindow cw = new ConfirmWindow(selected);
                cw.Closed += new EventHandler(cw_Closed);
                cw.Show();
            }
        }

        void cw_Closed(object sender, EventArgs e)
        {
            ConfirmWindow cw = (ConfirmWindow)sender;
            if (cw.DialogResult == true)
            {
                pmWebServiceClient webs = new pmWebServiceClient();

                webs.DeleteProjectCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(webs_DeleteProjectCompleted);
                webs.DeleteProjectAsync(Convert.ToInt32(selected.Id));
            }
        }

        void webs_DeleteProjectCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            MessageBox.Show("Project was deleted successfully!");
            ShowOwnedProject();
        }

        //PROFILE - BEGIN
        //on profile button click, show the profile
        private void buttProfile_Click(object sender, RoutedEventArgs e)
        {
            Profile p = new Profile(curUser);
            p.Closed += new EventHandler(pClose);
            p.Show();
        }
        void pClose(object sender, EventArgs e)
        {
            Profile p = (Profile)sender;            

            if (p.DialogResult == true)
            {
                // Password
                if (p.passboxOldPassword.Password != "")
                    curUser.user_password = p.passboxNewPassword.Password;

                // First Name
                if (p.txtboxFirstName.Text == "")
                    curUser.user_firstname = "N/A";
                else
                    curUser.user_firstname = p.txtboxFirstName.Text;

                // Last Name
                if (p.txtboxLastName.Text == "")
                    curUser.user_lastname = "N/A";
                else
                    curUser.user_lastname = p.txtboxLastName.Text;

                // Bday
                if (p.datepickBirthday.SelectedDate.HasValue == false)
                    curUser.user_birthday = Convert.ToDateTime("1/1/1900");
                else
                    curUser.user_birthday = p.datepickBirthday.SelectedDate;

                // Sex
                curUser.user_sex = p.comboSex.SelectedIndex - 1;

                // Address
                if (p.txtboxAddress.Text == "")
                    curUser.user_address = "N/A";
                else
                    curUser.user_address = p.txtboxAddress.Text;

                // Phone Number
                if (p.txtboxPhoneNumber.Text == "")
                    curUser.user_phone = "N/A";
                else
                    curUser.user_phone = p.txtboxPhoneNumber.Text;

                //// Naive code to fix bug
                pmWebServiceClient tido = new pmWebServiceClient();

                tido.UpdateUserDetailsCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(UserControlPanel_UpdateFolderDetailCompleted);
                tido.UpdateUserDetailsAsync(Convert.ToInt32(curUser.user_id), curUser);

                ++index;
            }
        }

        void es_UpdateUserDetailsCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            MessageBox.Show("User is updated successfully!");
            GetUserByEmail();
        }

        void UserControlPanel_UpdateFolderDetailCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            MessageBox.Show("User is updated successfully!");
        }

        void ws_UpdateUserDetailsCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            MessageBox.Show("User is updated successfully!");
            GetUserByEmail();
        }

        //PROFILE - END


        //OPEN OWNED PROJECT
        private void buttOpenOwnedProject_Click(object sender, RoutedEventArgs e)
        {
            //if there's an owned project is chosen to view, 
            //pass the project id to owned project page
            //if no project chosen, do nothing
            if (datagridOwnedProject.SelectedIndex >= 0)
            {
                int pid;

                selected = (OwnedProjectItem)datagridOwnedProject.SelectedItem;
                pid = Convert.ToInt32(selected.Id);

                PageSwitch ps = this.Parent as PageSwitch;
                ps.Navigate(new OwnedProject(pid));
            }
            else
            {
                MessageBox.Show("Choose a project to open!");
            }
        }

        //OPEN INVOLVED PROJECT
        private void buttOpenInvolvedProject_Click(object sender, RoutedEventArgs e)
        {
            //if there's an involved project is chosen to view,
            //pass the project id to involved project page
            //if no project chosen, do nothing
            if (datagridInvolvedProject.SelectedIndex >= 0)
            {
                int pid;
                selected_involved = (InvolvedProjectItem)datagridInvolvedProject.SelectedItem;
                pid = Convert.ToInt32(selected_involved.Id);

                PageSwitch ps = this.Parent as PageSwitch;
                ps.Navigate(new InvolvedProject(pid));
            }
            else
            {
                MessageBox.Show("Choose a project to open!");
            }
        }

    }

}
